import { ref, reactive, type Ref } from "vue";
import { defineStore } from "pinia";
import { $ } from "@visual/utils/utils";
import { nanoid } from "nanoid";
import { decomposeComponent, decomposeComponent2, createGroupStyle } from "@visual/utils";
import { commonAttr, commonStyle } from "../custom-component/component-list";
import { useComponent } from "@visual/stores";
import { PxMessage } from "px-ui";

type AreaData = {
  style: {
    top: Number;
    left: Number;
    width: Number;
    height: Number;
  };
  lable?: String;
  components: Array<any>;
};
export const useCompose = defineStore("compose", () => {
  const editor: Ref<HTMLDivElement | null> = ref(null);
  const areaData: AreaData = reactive({
    style: {
      top: 0,
      left: 0,
      width: 0,
      height: 0
    },
    components: []
  });
  function getEditor() {
    editor.value = $("#editor");
  }
  function setAreaData(data) {
    Object.assign(areaData, data);
  }

  function compose(componentData, groupAttr) {
    const components = [];
    areaData.components.forEach(component => {
      if (component.component != "Group") {
        components.push(component);
      } else {
        // 如果要组合的组件中，已经存在组合数据，则需要提前拆分
        const parentStyle = { ...component.style };
        const subComponents = component.propValue.components;
        const editorRect = editor.value.getBoundingClientRect();

        if (subComponents && Array.isArray(subComponents)) {
          subComponents.forEach(component => {
            decomposeComponent(component, editorRect, parentStyle);
          });
        }

        components.push(...component.propValue.components);
      }
    });
    let groupComponent = {
      id: nanoid(),
      component: "Group",
      label: areaData.label ? areaData.label : "组合",
      icon: "zuhe",
      belong: "middle",
      ...commonAttr,
      style: {
        ...commonStyle,
        ...areaData.style,
        visibility: "visible",
        display: "block"
      },
      propValue: { components, filter: "" }
    };
    if (groupAttr) {
      Object.assign(groupComponent, groupAttr);
    }

    createGroupStyle(groupComponent);
    const { addComponent, setCurComponent } = useComponent();
    // Assuming addComponent and batchDeleteComponent are actions in another store

    addComponent({
      component: groupComponent
    });

    // eventBus.emit("hideArea");

    batchDeleteComponent(componentData, areaData.components);
    setCurComponent({
      component: componentData[componentData.length - 1],
      index: componentData.length - 1
    });

    areaData.components = [];
  }
  // 将已经放到 Group 组件数据删除，也就是在 componentData 中删除，因为它们已经从 componentData 挪到 Group 组件中了
  function batchDeleteComponent(componentData, deleteData) {
    deleteData.forEach(component => {
      for (let i = 0, len = componentData.value.length; i < len; i++) {
        if (component.id == componentData.value[i].id) {
          componentData.value.splice(i, 1);
          break;
        }
      }
    });
  }

  function decompose(curComponent) {
    const parentStyle = { ...curComponent.value.style };
    const components = curComponent.value.propValue.components;
    const editorRect = editor.value.getBoundingClientRect();
    const { deleteComponent, addComponent } = useComponent();

    deleteComponent();
    components.forEach(component => {
      decomposeComponent(component, editorRect, parentStyle);
      addComponent({ component });
    });
  }
  function syncGroupStyle(componentData) {
    const group = componentData.value.filter(item => item.component == "Group");
    const editorRect = editor.value.getBoundingClientRect();

    group.forEach(groupItem => {
      const { display, visibility } = groupItem.style;
      if (display !== "none" && visibility !== "hidden")
        groupItem.propValue.components.forEach(comp => {
          decomposeComponent2(comp, editorRect, groupItem.style);
        });
    });
    PxMessage.success("分组样式同步完成");
  }
  function decomposediff(diff, curComponent) {
    const parentStyle = { ...curComponent.value.style };
    const components = diff;
    const editorRect = editor.value.getBoundingClientRect();
    const { addComponent } = useComponent();

    components.forEach(component => {
      decomposeComponent(component, editorRect, parentStyle);
      addComponent({ component });
    });
  }

  // function createGroupStyle(groupComponent: { style: any; propValue: any[]; events: {}; groupStyle: {}; isLock: boolean; collapseName: string; id: string; component: string; label: string; icon: string; }) {
  //   throw new Error("Function not implemented.");
  // }
  return {
    areaData,
    editor,
    getEditor,
    setAreaData,
    compose,
    batchDeleteComponent,
    decompose,
    decomposediff,
    syncGroupStyle
  };
});
